#include "_2misc.h"

char dynmem[1024*1024];

volatile enum {
    BP_BSS_CLEANED=0x1010111,
    AP_ARCH_INITED
} system_initialized;

static void wait_core_online()
{
    system_initialized = BP_BSS_CLEANED;

    int onlined = 0;
    boolean status[CFG_CORE_NUM];

    for(int i=0; i<CFG_CORE_NUM; i++)
    {
        status[i] = False;
    }

    arch_enable_local_irq(0);

    for(int i=0; i<10000; i++)
    {
        for(int c=0; c<CFG_CORE_NUM; c++)
        {
            if(!status[c])
            {
                if(arch_is_core_online(c))
                {
                    onlined++;
                    status[c] = True;
                }
            }
        }
        if(onlined == CFG_CORE_NUM)
        {
            break;
        }
        for(int j=0; j<1000; j++)
        {
        }
    }
    for (int i = 0; i < CFG_CORE_NUM; i++)
    {
        if (status[i])
        {
            kprint("core %d \033[92monline\033[0m\n", i);
        }
        else
        {
            kprint("core %d \033[91moffline\033[0m\n", i);
        }
    }

    kprint("Total %d core(s) online...\n", onlined);
}

__attribute__((naked)) 
__attribute__((noreturn)) 
void startup_astral()
{
    build_sys_arg();
    init_ff_alloc(dynmem, 1024*1024);

    device_init();
    banner();
    arch_init();
    irqm_init();
    shed_init();
    timer_init();

    wait_core_online();

    static_task_init();

    system_initialized = True;
    schedule();
}

__attribute__((naked)) 
__attribute__((noreturn))
void startup_apcore()
{
    while(BP_BSS_CLEANED != system_initialized){}

    arch_init();
    schedule();
}